package _base0to1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1396. 设计地铁系统
 */
public class No1396 {
    private int id = 0;
    private final Map<Integer, Underground> db;
    private final Map<String, List<Integer>> startStationIndexs;

    private class Underground {
        int id;
        String startStation;
        int startTime;
        String endStation;
        int endTime;

        public Underground() {
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getStartStation() {
            return startStation;
        }

        public void setStartStation(String startStation) {
            this.startStation = startStation;
        }

        public int getStartTime() {
            return startTime;
        }

        public void setStartTime(int startTime) {
            this.startTime = startTime;
        }

        public String getEndStation() {
            return endStation;
        }

        public void setEndStation(String endStation) {
            this.endStation = endStation;
        }

        public int getEndTime() {
            return endTime;
        }

        public void setEndTime(int endTime) {
            this.endTime = endTime;
        }
    }

    public No1396() {
        this.db = new HashMap<>();
        this.startStationIndexs = new HashMap<>();
    }

    public void checkIn(int id, String stationName, int t) {
        Underground underground = new Underground();
        underground.setId(id);
        underground.setStartStation(stationName);
        underground.setStartTime(t);
        // 持久化到数据库
        this.db.put(++this.id, underground);
        // 对入站记录建立普通索引
        if (this.startStationIndexs.containsKey(stationName)) {
            this.startStationIndexs.get(stationName).add(this.id);
        } else {
            ArrayList<Integer> ids = new ArrayList<>();
            ids.add(this.id);
            this.startStationIndexs.put(stationName, ids);
        }
    }

    public void checkOut(int id, String stationName, int t) {
        for (Underground item : this.db.values()) {
            if (item.id == id && item.endStation == null) {
                item.setEndStation(stationName);
                item.setEndTime(t);
            }
        }
    }

    public double getAverageTime(String startStation, String endStation) {
        long startTimes = 0, endTimes = 0, num = 0;
        for (Integer id : this.startStationIndexs.get(startStation)) {
            Underground item = this.db.get(id);
            if (item.getEndStation() == null || !item.getEndStation().equals(endStation)) continue;
            startTimes += item.getStartTime();
            endTimes += item.getEndTime();
            num++;
        }
        if (num == 0) return 0;
        return (double) (endTimes - startTimes) / num;
    }
}
